
#include <queue>
#include <pthread.h>

using namespace std;

template<class T>
class BlockQueue
{
public:
    BlockQueue(int cap)
    :_cap(cap)
    ,_product_wait_num(0)
    ,_consum_wait_num(0)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_product_cond,nullptr);
        pthread_cond_init(&_consum_cond,nullptr);
    }

    void Enqueue(const T& in)
    {
        pthread_mutex_lock(&_mutex);
        
        while(_q.size()== _cap)
        {
            _product_wait_num++;
            pthread_cond_wait(&_product_cond, &_mutex);

            _product_wait_num--;
        }

        _q.push(in);

        if(_consum_wait_num> 0)
        {
            pthread_cond_signal(&_consum_cond);
        }

        pthread_mutex_unlock(&_mutex);
    }

    void Pop(T* out)
    {
        pthread_mutex_lock(&_mutex);

        while(_q.empty())
        {
            _consum_wait_num++;

            pthread_cond_wait(&_consum_cond, &_mutex);
            _consum_wait_num--;

        }

        *out= _q.front();
        _q.pop();

        if(_product_wait_num> 0)
        {
            pthread_cond_signal(&_product_cond);
        }

        pthread_mutex_unlock(&_mutex);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_product_cond);
        pthread_cond_destroy(&_consum_cond);
    }




private:
    queue<T> _q;
    int _cap;//阻塞队列上限

    pthread_mutex_t _mutex;
    pthread_cond_t _product_cond;
    pthread_cond_t _consum_cond;

    int _product_wait_num;
    int _consum_wait_num;
};





